package io.kiki.sba.registry.remoting.http;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.net.NetUtil;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import java.net.InetSocketAddress;
import java.net.URI;


public class HttpChannel implements Channel {

    private final WebTarget webTarget;

    private final Client client;

    public HttpChannel(WebTarget webTarget, Client client) {
        this.webTarget = webTarget;
        this.client = client;
    }

    @Override
    public InetSocketAddress getRemoteAddress() {
        URI uri = webTarget.getUri();
        return new InetSocketAddress(uri.getHost(), uri.getPort());
    }

    @Override
    public InetSocketAddress getLocalAddress() {
        return NetUtil.getLocalSocketAddress();
    }

    @Override
    public boolean isConnected() {
        if (client instanceof org.glassfish.jersey.client.JerseyClient) {
            return !((org.glassfish.jersey.client.JerseyClient) client).isClosed();
        }
        return false;
    }

    @Override
    public Object getAttribute(String key) {
        return null;
    }

    @Override
    public void setAttribute(String key, Object value) {
    }

    @Override
    public Object getConnAttribute(String key) {
        return null;
    }

    @Override
    public void setChannelAttribute(String key, Object value) {
    }


    @Override
    public WebTarget getWebTarget() {
        return webTarget;
    }

    @Override
    public void close() {
        client.close();
    }
}
